package com.enzoism.springboot.dive.service;

import com.enzoism.springboot.dive.dao.UserDao;
import com.enzoism.springboot.dive.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@CacheConfig(cacheNames = "userCache") // 默认缓存名称
public class UserService {
    
    @Autowired
    private UserDao userDao;
    
    /**
     * 新增用户
     * 新增后清除相关缓存
     */
    @CacheEvict(key = "'allUsers'", allEntries = true)
    public User addUser(User user) {
        log.info("开始新增用户：{}", user);
        return userDao.insert(user);
    }
    
    /**
     * 根据复合key查询用户
     * 使用复合key作为缓存key
     */
    @Cacheable(key = "#userId + '_' + #roleId", unless = "#result == null")
    public User getUserByCompositeKey(Long userId, Long roleId) {
        log.info("缓存未命中，查询数据库获取用户：userId={}, roleId={}", userId, roleId);
        return userDao.selectByCompositeKey(userId, roleId);
    }
    
    /**
     * 查询所有用户
     */
    @Cacheable(key = "'allUsers'", unless = "#result == null || #result.isEmpty()")
    public List<User> getAllUsers() {
        log.info("缓存未命中，查询数据库获取所有用户");
        return userDao.selectAll();
    }
    
    /**
     * 根据userId查询用户列表
     */
    @Cacheable(key = "'userId_' + #userId", unless = "#result == null || #result.isEmpty()")
    public List<User> getUsersByUserId(Long userId) {
        log.info("缓存未命中，查询数据库获取用户列表：userId={}", userId);
        return userDao.selectByUserId(userId);
    }
    
    /**
     * 根据roleId查询用户列表
     */
    @Cacheable(key = "'roleId_' + #roleId", unless = "#result == null || #result.isEmpty()")
    public List<User> getUsersByRoleId(Long roleId) {
        log.info("缓存未命中，查询数据库获取用户列表：roleId={}", roleId);
        return userDao.selectByRoleId(roleId);
    }
    
    /**
     * 更新用户
     * 更新后清除该用户的缓存和相关列表缓存
     */
    @Caching(
        evict = {
            @CacheEvict(key = "#user.userId + '_' + #user.roleId"),
            @CacheEvict(key = "'userId_' + #user.userId"),
            @CacheEvict(key = "'roleId_' + #user.roleId"),
            @CacheEvict(key = "'allUsers'", allEntries = true)
        }
    )
    public User updateUser(User user) {
        log.info("开始更新用户：{}", user);
        return userDao.update(user);
    }
    
    /**
     * 删除用户
     * 删除后清除相关缓存
     */
    @Caching(
        evict = {
            @CacheEvict(key = "#userId + '_' + #roleId"),
            @CacheEvict(key = "'userId_' + #userId"),
            @CacheEvict(key = "'roleId_' + #roleId"),
            @CacheEvict(key = "'allUsers'", allEntries = true)
        }
    )
    public boolean deleteUser(Long userId, Long roleId) {
        log.info("开始删除用户：userId={}, roleId={}", userId, roleId);
        return userDao.delete(userId, roleId);
    }
    
    /**
     * 判断用户是否存在
     */
    @Cacheable(key = "'exists_' + #userId + '_' + #roleId")
    public boolean existsUser(Long userId, Long roleId) {
        log.info("缓存未命中，查询数据库判断用户是否存在：userId={}, roleId={}", userId, roleId);
        return userDao.exists(userId, roleId);
    }
    
    /**
     * 手动清除指定用户的缓存
     */
    @CacheEvict(key = "#userId + '_' + #roleId")
    public void evictUserCache(Long userId, Long roleId) {
        log.info("手动清除用户缓存：userId={}, roleId={}", userId, roleId);
    }
    
    /**
     * 清除所有用户缓存
     */
    @CacheEvict(allEntries = true)
    public void evictAllUsersCache() {
        log.info("清除所有用户缓存");
    }
}